package com.prs.crm.service.hr.impl;


import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;

import com.prs.crm.dao.hr.RoleDao;
import com.prs.crm.domain.hr.Role;
import com.prs.crm.domain.sys.Menu;
import com.prs.crm.service.hr.RoleService;
import com.prs.crm.service.impl.BaseServiceImpl;
import com.prs.crm.service.sys.MenuService;
import com.prs.crm.service.sys.ModuleService;

public class RoleServiceImpl extends BaseServiceImpl<Role,RoleDao> implements RoleService{

	@Autowired
	private ModuleService moduleService;
	
	@Autowired
	private MenuService menuService;
	
	public ModuleService getModuleService() {
		return moduleService;
	}

	public void setMenuService(MenuService menuService) {
		this.menuService = menuService;
	}

	public MenuService getMenuService() {
		return menuService;
	}

	public void setModuleService(ModuleService moduleService) {
		this.moduleService = moduleService;
	}

	
	
	public 	List<Role> getAllRoles()
	{
		return this.getDao().getAllRoles();
	}
	
	public void grant(Role role,String[] moduleids)
	{
		role.getModules().clear();
		for (String moduleid:moduleids)
		{
			if (moduleid!=null && moduleid.trim().length()>0
					&& Integer.valueOf(moduleid)>0)
			{
				role.addModule(moduleService.get(Integer.valueOf(moduleid)));
			}
		}
		super.save(role);
	}
	
	public void grantMenu(Role role,String[] menuids)
	{
		role.getMenus().clear();
		for (String menuid:menuids)
		{
			if (menuid!=null && menuid.trim().length()>0
					&& Integer.valueOf(menuid)>0)
			{
				role.addMenu(menuService.get(Integer.valueOf(menuid)));
			}
		}
		super.save(role);
	}

	@Override
	public void grantMenuByRootMenu(Role role,Menu rootMenu,String[] checkedMenuIds, String[] uncheckedMenuIds) {
		Set<Menu> menus = role.getMenus();
		for(String checked : checkedMenuIds){
			if (checked!=null && checked.trim().length()>0 && Integer.valueOf(checked)>0)
			{
				Menu menu = menuService.get(Integer.valueOf(checked));
				if(!menus.contains(menu)){
					menus.add(menu);
				}
			}
		}
		for (String unchecked : uncheckedMenuIds)
		{
			if (unchecked!=null && unchecked.trim().length()>0 && Integer.valueOf(unchecked)>0)
			{
				Menu menu = menuService.get(Integer.valueOf(unchecked));
				if(menus.contains(menu)){
					menus.remove(menu);
				}
			}
		}
		role.addMenu(rootMenu);
		for(Menu menu : menus){
			role.addMenu(menu);
		}
		super.save(role) ;
	}

	@Override
	public Role getByNameRole(String name) {
		// TODO Auto-generated method stub
		return this.getDao().getByNameRole(name);
	}
}
